package com.wps.wdztv6.controller.callback;

import com.alibaba.fastjson.JSON;
import com.wps.wdztv6.common.R;
import com.wps.wdztv6.common.ResultEnum;
import com.wps.wdztv6.domain.WdztResult;
import com.wps.wdztv6.domain.edit.*;
import com.wps.wdztv6.entity.ThirdFile;
import com.wps.wdztv6.service.FileService;
import com.wps.wdztv6.service.UserInfoService;
import com.wps.wdztv6.service.WdztService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 在线编辑与预览回调接口，2合一
 */
@RestController
@RequestMapping("/wdzt/v6")
@Log4j2
public class EditAndPreviewCallbackController {

    @Autowired
    private FileService fileService;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 文件信息回调接口
     * @param fileId 文件id，中台回调本接口时带来 必传
     * @param webofficeToken 启用前段jssdk鉴权后发过来，如果未开启则一般为空
     * @return 文件信息
     */
    @GetMapping("/v1/3rd/file/info")
    public Object v13rdFileInfo(@RequestParam(value = "fileId")String fileId,
                                @RequestParam(value = "webofficeToken",required = false)String webofficeToken,
                                HttpServletRequest request, HttpServletResponse res){
        Map<String,String[]> queryMap = request.getParameterMap();
        log.info("/v1/3rd/file/info x-weboffice-file-id:{} x-wps-weboffice-token:{}",fileId,webofficeToken);
        log.info("/v1/3rd/file/info queryMap:{}",queryMap);

        R<ThirdFile> thirdFileR = fileService.getLatestFileByFileId(fileId);

        if (thirdFileR.getResult() != ResultEnum.SUCCESS.getCode()) {
            log.info("文件不存在:{}",fileId);
            res.setStatus(400);
            return WdztResult.failed("文件不存在存在","请检查文件信息是否正确");
        }

        ThirdFile thirdFile = thirdFileR.getData();

        FileInfoCallback.FileMeta.UserAccessControlList userAcl = FileInfoCallback.FileMeta.UserAccessControlList.builder()
                .copy(1)
                .export(1)
                .history(1)
                .rename(1)
                .print(1)
                .build();

        FileInfoCallback.User user = FileInfoCallback.User.builder()
                .id("oa")
                .name("oa")
                .avatarUrl(userInfoService.genUserAvatarLink("oa"))
                .permission("write")
                .build();
        FileInfoCallback.FileMeta fileMeta = FileInfoCallback.FileMeta.builder()
                .id(fileId)
                .name(thirdFile.getName())
                .version(thirdFile.getVersion())
                .size(thirdFile.getSize())
                .userAcl(userAcl)
                .creator("oa")
                .modifier("oa")
                .watermark(FileInfoCallback.FileMeta.Watermark.builder()
                        .type(0)
                        .build())
                .createTime(thirdFile.getCreateTime())
                .modifyTime(thirdFile.getCreateTime())
                .downloadUrl(fileService.getDownloadUrl(fileId,thirdFile.getVersion()))
                .build();

        FileInfoCallback response = FileInfoCallback.builder()
                .user(user)
                .file(fileMeta)
                .build();
        log.info("返回信息:{}",JSON.toJSONString(response));
        return response;
    }

    /**
     * 中台根据用户id请求获取用户信息回调接口
     * @param fileId 文件id
     * @param webofficeToken
     * @param bodyMap 用户ids数组
     * @return 用户数组信息
     */
    @PostMapping("/v1/3rd/user/info")
    public UserInfoCallback v13rdUserInfo(@RequestHeader(value = "x-weboffice-file-id",required = false)String fileId,
                                        @RequestHeader(value = "x-wps-weboffice-token",required = false)String webofficeToken,
                                        @RequestBody(required = false) HashMap<String,List<String>> bodyMap){
        log.info("/v1/3rd/user/info ids:{} :{} {}",bodyMap,fileId,webofficeToken);
        List<UserInfoCallback.User> users = new ArrayList<>();
        for(String id : bodyMap.get("ids")) {
            UserInfoCallback.User user = UserInfoCallback.User.builder().id(id).name("用户"+id).avatarUrl(userInfoService.genUserAvatarLink(id)).build();
            users.add(user);
        }
        UserInfoCallback response = UserInfoCallback.builder().users(users).build();
        log.info("文档中台获取用户信息回调接口返回信息:{}", JSON.toJSONString(response));
        return response;
    }

    @PostMapping("/v1/3rd/file/save")
    public UploadFileNewVersionCallback v13rdFileSave(@RequestHeader(value = "x-weboffice-file-id",required = false)String fileId,
                                                      @RequestHeader(value = "x-wps-weboffice-token",required = false)String webofficeToken,
                                                      @RequestParam(value = "file") MultipartFile file){
        log.info("/v1/3rd/file/save :{} {}",fileId,webofficeToken);
        UploadFileNewVersionCallback response;
        if (file != null && !file.isEmpty()) {
            R<ThirdFile> thirdFileR = fileService.saveFileNewVersion(fileId,file);
            if (thirdFileR.getResult() == ResultEnum.SUCCESS.getCode()) {
                UploadFileNewVersionCallback.File newVersionFile = UploadFileNewVersionCallback.File.builder()
                        .id(fileId)
                        .name(thirdFileR.getData().getName())
                        .size(thirdFileR.getData().getSize())
                        .version(thirdFileR.getData().getVersion())
                        .downloadUrl(fileService.getDownloadUrl(fileId,thirdFileR.getData().getVersion()))
                        .build();
                response = UploadFileNewVersionCallback.builder().file(newVersionFile).build();
            } else {
                response = UploadFileNewVersionCallback.builder().build();
            }
        } else {
            response = UploadFileNewVersionCallback.builder().build();
        }
        log.info("文件保存新版本:{}", JSON.toJSONString(response));
        return response;
    }

    @PutMapping("/v1/3rd/file/rename")
    public FileRenameCallback v13rdFileRename(@RequestHeader(value = "x-weboffice-file-id",required = false)String fileId,
                                              @RequestHeader(value = "x-wps-weboffice-token",required = false)String webofficeToken,
                                              @RequestParam String name){
        return FileRenameCallback.builder().build();
    }

    @PostMapping("/v1/3rd/file/online")
    public OnlineEditCallback v13rdFileOnlie(@RequestHeader(value = "x-weboffice-file-id",required = false)String fileId,
                                             @RequestHeader(value = "x-wps-weboffice-token",required = false)String webofficeToken,
                                             @RequestBody(required = false) UserCallbackIds ids) {
        log.info("/v1/3rd/file/online :{} {}",fileId,webofficeToken);
        log.info("文件:{} 在线人数:{}",fileId, JSON.toJSONString(ids));
        return OnlineEditCallback.builder().build();
    }

    @GetMapping("/v1/3rd/file/version/{version}")
    public FileVersionCallback v13rdFileVersion(@RequestHeader(value = "x-weboffice-file-id",required = false)String fileId,
                                                @RequestHeader(value = "x-wps-weboffice-token",required = false)String webofficeToken,
                                                @PathVariable(name = "version")Integer version) {
        log.info("/v1/3rd/file/version/{} :{} {}",version,fileId,webofficeToken);
        R<ThirdFile> versionFileR = fileService.getFileByVersion(fileId,version);
        FileVersionCallback.File versionFile = FileVersionCallback.File.builder()
                .id(fileId)
                .name(versionFileR.getData().getName())
                .version(version)
                .creator("oa")
                .modifier("oa")
                .modifyTime(versionFileR.getData().getUpdateTime())
                .creator("oa")
                .createTime(versionFileR.getData().getCreateTime())
                .size(versionFileR.getData().getSize())
                .downloadUrl(fileService.getDownloadUrl(fileId,version))
                .build();
        FileVersionCallback response = FileVersionCallback.builder().file(versionFile).build();
        log.info("返回特定版本历史信息:{}",JSON.toJSONString(response));
        return response;
    }

    @GetMapping("/v1/3rd/file/history")
    public FileVersionsCallback v13rdFileHistory(@RequestHeader(value = "x-weboffice-file-id",required = false)String fileId,
                                                 @RequestHeader(value = "x-wps-weboffice-token",required = false)String webofficeToken) {
        log.info("/v1/3rd/file/history :{} {}",fileId,webofficeToken);
        R<List<ThirdFile>> versionsFileR = fileService.getFileHistory(fileId);

        List<FileVersionsCallback.File> fileList = new ArrayList<>();

        for(ThirdFile thirdFile: versionsFileR.getData()) {
            fileList.add(
                    FileVersionsCallback.File.builder()
                            .id(fileId)
                            .name(thirdFile.getName())
                            .createTime(thirdFile.getCreateTime())
                            .size(thirdFile.getSize())
                            .downloadUrl(fileService.getDownloadUrl(fileId,thirdFile.getVersion()))
                            .modifier(
                                    FileVersionsCallback.File.User.builder()
                                            .id("oa")
                                            .name("oa")
                                            .avatarUrl(userInfoService.genUserAvatarLink("oa"))
                                            .build()
                            )
                            .creator(FileVersionsCallback.File.User.builder()
                                    .id("oa")
                                    .name("oa")
                                    .avatarUrl(userInfoService.genUserAvatarLink("oa"))
                                    .build())
                            .modifyTime(thirdFile.getCreateTime())
                            .build()
            );
        }
        FileVersionsCallback response = FileVersionsCallback.builder().files(fileList).build();
        log.info("返回历史版本列表信息:{}",JSON.toJSONString(response));
        return response;
    }

    @PostMapping("/v1/3rd/onnotify")
    public void v13rdOnNotify(@RequestHeader(value = "x-weboffice-file-id",required = false)String fileId,
                              @RequestHeader(value = "x-wps-weboffice-token",required = false)String webofficeToken,
                              @RequestBody(required = false) OnNotifyCallback body) {
        log.info("结果:{}", body);
    }
}
